package org.jet.emall.reptile.handler;

import com.github.pagehelper.PageHelper;
import org.jet.emall.mapper.TbProdSkuImageMapper;
import org.jet.emall.mapper.TbProdSkuMapper;
import org.jet.emall.mapper.TbProdSpuImageMapper;
import org.jet.emall.mapper.TbProdSpuMapper;
import org.jet.emall.po.*;
import org.jet.emall.reptile.utils.HttpClientUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class ImageUrlHandler {

    @Autowired
    private TbProdSkuMapper prodSkuMapper;

    @Autowired
    private TbProdSpuMapper prodSpuMapper;

    @Autowired
    private TbProdSkuImageMapper prodSkuImageMapper;

    @Autowired
    private TbProdSpuImageMapper prodSpuImageMapper;

    final String flag = ".com/";

    boolean test = false;

    ExecutorService threadPool = Executors.newFixedThreadPool(20);
    private long count=0;


    public void handle() {
        handleSkuSelection();
//        handleSpuImages();
//        handleSkuImages();
        while (true){
            try {
                Thread.sleep(30000);
                System.out.println("主线程["+Thread.currentThread().getId()+"]正在等待中.........................................");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private void handleSkuSelection(){
        int pageSize = 50;

        long totals = prodSkuMapper.countByExample(null);
        for (int pageNum = 1; ; pageNum++) {
            if((pageNum-1)*pageSize > totals ) {
                break;
            }
            final int num = pageNum;
            threadPool.execute(() -> {
                PageHelper.startPage(num, pageSize);
                List<TbProdSku> tbProdSkus = prodSkuMapper.selectByExample(null);

                tbProdSkus.forEach(sku->{
                    String code = sku.getCode();
                    String url ="http://item.jd.com/"+code+".html";
                    String productHtml = null;
                    try {
                        productHtml = HttpClientUtils.doGet(url);

                        Document document = Jsoup.parse(productHtml);
                        Element element = document.getElementById("choose-attrs");
                        if(code.equals("100007958758")){
                            System.out.println("url="+url+",skucode="+sku.getCode()+",document="+document);

                            new Scanner(System.in).next();
                        }

                        if(element!=null&& test==false){
                            test = true;
                            System.out.println("url="+url+",skucode="+sku.getCode()+",document="+document);

                        }
                       // Elements select = document.select("#choose-attrs");
                       // System.out.println("["+Thread.currentThread().getId()+"]code="+sku.getCode()+",select="+select.size()+"," +
                               // "emement="+element);



                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                });


            });

        }
    }

    private void handleSpuImages(){
//        File file = new File(imagesDir);
//        if (!file.exists()) {
//            file.mkdir();
//        }
        int pageSize = 50;
        System.out.println("开始SPU下载图片");
        long totals = prodSpuMapper.countByExample(null);
        for (int pageNum = 1; ; pageNum++) {
            if((pageNum-1)*pageSize > totals ) {
                break;
            }
            final int num = pageNum;
            threadPool.execute(() -> {
                PageHelper.startPage(num, pageSize);

                List<TbProdSpu> tbProdSpus = prodSpuMapper.selectByExample(null);

                TbProdSpuImageExample ex = new TbProdSpuImageExample();
                for (TbProdSpu tbProdSpu : tbProdSpus) {
                    ex.clear();
                    ex.createCriteria().andSpuIdEqualTo(tbProdSpu.getId());
                    List<TbProdSpuImage> tbProdSpuImages = prodSpuImageMapper.selectByExample(ex);
                    for (TbProdSpuImage tbProdSpuImage : tbProdSpuImages) {
                        int i = tbProdSpuImage.getImage().indexOf(flag);
                        tbProdSpuImage.setImage(tbProdSpuImage.getImage().substring(i+flag.length()));
                        prodSpuImageMapper.updateByPrimaryKeySelective(tbProdSpuImage);
                    }
                }
            });

        }


    }


    private void handleSkuImages(){
//        File file = new File(imagesDir);
//        if (!file.exists()) {
//            file.mkdir();
//        }
        int pageSize = 100;
        System.out.println("开始下载图片");
        long totals = prodSkuMapper.countByExample(null);
        for (int pageNum = 1; ; pageNum++) {
            if((pageNum-1)*pageSize > totals ) {
                break;
            }
            int num = pageNum;
            threadPool.execute(() -> {
                PageHelper.startPage(num, pageSize);
                List<TbProdSku> tbProdSkus = prodSkuMapper.selectByExample(null);
                TbProdSkuImageExample ex = new TbProdSkuImageExample();

                for (TbProdSku tbProdSku : tbProdSkus) {
                    ex.clear();
                    ex.createCriteria().andSkuIdEqualTo(tbProdSku.getId());
                    List<TbProdSkuImage> skuImageList = prodSkuImageMapper.selectByExample(ex);
                    for(TbProdSkuImage skuImage:skuImageList){
                        int i = skuImage.getImage().indexOf(flag);
                        skuImage.setImage(skuImage.getImage().substring(i+flag.length()));
                        int j = skuImage.getLargeImage().indexOf(flag);
                        skuImage.setLargeImage(skuImage.getLargeImage().substring(j+flag.length()));
                        prodSkuImageMapper.updateByPrimaryKey(skuImage);
                    }
                }
            });

        }


    }

//    private void saveFile(String imagesDir, String url) throws IOException {
//
//        ImageModel imageModel = HttpClientUtils.doDownloadImage(url);
//        String filePath = imagesDir + "/" + imageModel.getFileName();
//        String dir = filePath.substring(0, filePath.lastIndexOf("/"));
//        File dirFile = new File(dir);
//        if (!dirFile.exists()) {
//            dirFile.mkdirs();
//        }
//        File file = new File(filePath);
//        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
//        outputStream.write(imageModel.getData());
//        outputStream.flush();
//
//    }

}
